package cn.wolfcode.service.impl;

import cn.wolfcode.config.DeepSeekProperties;
import cn.wolfcode.domain.Strategy;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class DeepSeekService {


    @Autowired
    private DeepSeekProperties properties;

    /*
     *基于私有数据（es库中的strategy）构建上下文并想DeepSeek提问
     * 参数1：用户发出的问题
     * 参数2：私有库的攻略数组
     * */
    public String askWithStrategies(String question, List<Strategy> strategies){
        //用于构建字符串的对象，使用‘\
        StringJoiner joiner = new StringJoiner("\n\n");
        joiner.add("你是一个严谨的助理。请仅基于提供的私有知识库片段回答结合互联网，不要编造拓展。如果资料不足，请明确说明不知道。\n\n" +
                "以下是来自私有库的内容片段（JSON）： ");
        //遍历查询
        for (Strategy strategy : strategies) {
            String json = JSON.toJSONString(strategy);
            joiner.add(json);
        }
        //结合私库请求的数据
        String systemPrompt = joiner.toString();

        //整合发送给大家大模型的消息，
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", systemPrompt);
        messages.add(systemMessage);
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", question);
        messages.add(userMessage);

        Map<String, Object> openAiChatRequest = new HashMap<>();
        openAiChatRequest.put("model", properties.getModel());
        openAiChatRequest.put("messages", messages);
        openAiChatRequest.put("temperature", 0.7);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(properties.getApiKey());

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(openAiChatRequest, httpHeaders);

        String url = properties.getBaseUrl();

        url = url+"/chat/completions";

        RestTemplate restTemplate = new RestTemplate();
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);

        System.err.println("应答结果：");
        System.err.println(map);
        System.err.println("========");

        if(map == null || map.get("choices") == null){
            return "(无回答)";
        }
        List choices = (List) map.get("choices");
        if(choices.isEmpty()){
            return "(无回答)";
        }

        Map choice = (Map) choices.get(0);
        Map message = (Map) choice.get("message");
        String content = (String) message.get("content");

        return content;
    }


}

